import { computed, reactive, ref } from "vue"
import { useRoute, useRouter } from "vue-router"
import { getAxios } from "/axios"

export function useList(reloadCategory) {
	const route = useRoute()
	const router = useRouter()

	const formData = reactive({
		pageNum: 1,
		pageSize: 10,

		isVideo: 2,
		fileCategorys: "",
		type: "03",

		fileName: "",
		fileOwner: "",
		fileContent: "",
		fileTags: "",
		keywords: "",

		startTime: "",
		endTime: "",
		fileType: "",
	})

	const list = ref([])
	const total = ref(0)

	const keywordName = computed(() => {
		switch (formData.type) {
			case "00":
				return "fileName"
			case "01":
				return "fileOwner"
			case "02":
				return "fileContent"
			case "04":
				return "fileTags"
			default:
				return "keywords"
		}
	})

	const keywords = computed({
		get() {
			return formData[keywordName.value]
		},
		set(value) {
			formData[keywordName.value] = value
		},
	})

	if (route.query.content || route.query.type) {
		formData.type = route.query.type || "03"
		keywords.value = route.query.content || ""
	}

	async function getData() {
		const { searchHits, totalHits } = await getAxios(`/knowledge/es/search`, formData)

		list.value = searchHits
		total.value = totalHits

		reloadCategory()
		return searchHits
	}
	async function onSearch() {
		formData.pageNum = 1
		list.value = []
		total.value = 0

		router.replace({
			query: {
				...route.query,
				content: keywords.value,
				type: formData.type,
			},
		})

		return await getData()
	}

	onSearch()
	function onCurrentChange(current) {
		formData.pageNum = current
		getData()
	}

	function onRefreshQuery(size) {
		formData.pageSize = size
		getData()
	}

	return {
		formData,
		total,
		list,
		getData,
		onSearch,
		onCurrentChange,
		onRefreshQuery,

		keywordName,
		keywords,
	}
}
